package com.kehutong.wwin.service.service;

import com.kehutong.common.errcode.Result;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.urlconfig.WebUrlConfig;
import com.kehutong.common.util.Token;
import com.kehutong.wwin.service.entity.ResidentMap;
import com.kehutong.wwin.service.enums.MaterialType;
import com.kehutong.wwin.service.util.WwInHttpClient;
import com.kehutong.wxapi.request.AddMsgTemplateRequest;
import com.kehutong.wxapi.response.AddMsgTemplateResponse;
import com.kehutong.wxapi.service.ExternalContactService;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.EnumUtil;
import org.coraframework.util.Objects;

import java.util.ArrayList;
import java.util.List;

/**
 * 发送素材到企业微信
 *
 * @author: liukunlong
 * @date: 2021-03-12 10:59
 */
@WebService("/wwin-service/material/wwin")
public class ToWwinMaterialService {
    private static final Logger logger = LoggerFactory.getLogger(ToKhtDepartmentService.class);

    @Inject
    private WwInHttpClient httpClient;

    @Inject
    private JdbcSession jdbcSession;


    @Inject
    private FileUrlConfig fileUrlConfig;

    @Inject
    private WebUrlConfig webUrlConfig;

    @Inject
    private ExternalContactService externalContactService;

    /**
     * 发送素材
     * 群发
     * @throws Exception 异常
     */
    //@HasPermission({"admin:material:edit"})
    @ReqMapping("/send")
    public Object sendMsg(Token token, JSONObject khtJson) throws Exception {
        String id=khtJson.getString("id");
        String fileId=khtJson.getString("fileId");
        String shareUrl=khtJson.getString("shareUrl");
        String type=khtJson.getString("type");
        MaterialType materialType= EnumUtil.getEnum(MaterialType.class, type);
        switch (materialType) {
            case FILE:
                khtJson.put("url",fileUrlConfig.getFile(fileId, true));
                break;
            case IMAGE:
                khtJson.put("url",fileUrlConfig.getUrl("/file/view", "isBig", "true", "id",fileId));
                break;
            case VIDEO:
                khtJson.put("url",fileUrlConfig.getVideo(fileId));
                break;
            case SHARE:
                khtJson.put("url",shareUrl);
                break;
            case GRAPHIC:
                khtJson.put("url",webUrlConfig.getUrl("/weixin/#/graphic/show?id=" +id));
                break;
            case MINI_PROGRAM:
                //todo forwordFile
                break;
            default:
                break;
        }

        //转换客户通业主标志为外部联系人标志
        List<String> externalUserIds=new ArrayList<>();
        //外部用户标志
        JSONArray khtIds =JSONObject.parseArray(khtJson.getString("externalUserIds"));
        if(Objects.nonEmpty(khtIds)){
            for(Object obj:khtIds){
                String khtId = (String) obj;
                ResidentMap customerMap=getCustomerMapByKhtId(khtId);
                if(Objects.nonNull(customerMap)){
                    externalUserIds.add(customerMap.getId());
                }
            }
        }

        if(Objects.isEmpty(externalUserIds)){
            return Result.success(khtIds);
            //return Result.error(1,"外部联系人为空.");
        }

        AddMsgTemplateRequest addMsgTemplateRequest = new AddMsgTemplateRequest();
        addMsgTemplateRequest.setAccessToken(httpClient.getContactAccessToken(token));
        addMsgTemplateRequest.setChatType("single");
        addMsgTemplateRequest.setExternalUserid(externalUserIds);


        //如果当前发送的素材是小程序则发送小程序素材的形式发送到客户,否者发送图片链接素材的形式发给客户
        if (type.equalsIgnoreCase(MaterialType.MINI_PROGRAM.getId())) {
            AddMsgTemplateRequest.MiniprogramDTO miniprogram = new AddMsgTemplateRequest.MiniprogramDTO();
            miniprogram.setTitle(khtJson.getString("name"));
            miniprogram.setPicMediaId(khtJson.getString("media_id"));
            miniprogram.setAppid(khtJson.getString("descrition"));
            miniprogram.setPage(khtJson.getString("shareUrl"));
            addMsgTemplateRequest.setMiniprogram(miniprogram);

        } else {
            AddMsgTemplateRequest.LinkDTO link = new AddMsgTemplateRequest.LinkDTO();
            link.setTitle(khtJson.getString("name"));
            link.setDesc(khtJson.getString("descrition"));
            //todo 调用放根据类型构件建好
            link.setPicurl(fileUrlConfig.getUrl("/file/view", "isBig", "true", "id",fileId));
            link.setUrl(khtJson.getString("url"));
            addMsgTemplateRequest.setLink(link);
        }
        AddMsgTemplateResponse addMsgTemplateResponse = externalContactService.addMsgTemplate(addMsgTemplateRequest);
        if (addMsgTemplateResponse.getErrcode() != 0) {
            logger.error("ToWwinMaterialService.sendMsg 发送失败,errcode:{},errmsg:{}",addMsgTemplateResponse.getErrcode(),addMsgTemplateResponse.getErrmsg());
            return Result.success(khtIds);
        }

        return Result.success(castWxToKhtId(addMsgTemplateResponse.getFailList()));
    }

    /**
     * 转换微信客户标志集合为客户标志集合
     * @param ids 微信客户标志集合
     * @return 客户通标志集合
     */
    private List<String> castWxToKhtId(List<String> ids){
        List<String> khtList=new ArrayList<>();
        if(Objects.isEmpty(ids)){
            return khtList;
        }
        ids.forEach(id->{
            ResidentMap customerMap=getCustomerById(id);
            if(Objects.nonNull(customerMap)){
                khtList.add(customerMap.getKhtid());
            }
        });
        return khtList;
    }

    @ReqMapping("/forwardFile")
    public Object forwardFile(Token token, JSONObject khtJson) throws Exception {

        return null;
    }

    /**
     * 根据客户通标志获取客户映射信息
     * @param khtid 客户通标志
     * @return 映射信息
     */
    public ResidentMap getCustomerMapByKhtId(String khtid) {
        List<ResidentMap> exe = jdbcSession.findArray(ResidentMap.class)
                .eq("khtid",khtid).exe();
        if(Objects.isEmpty(exe)){
            return null;
        }
        return exe.get(0);
    }


    /**
     * 根据微信标志获取映射信息
     *
     * @param id 微信标志
     * @return 映射信息
     */
    public ResidentMap getCustomerById(String id) {
        return Pool.get(ResidentMap.class, id);
    }
}
